import { format } from 'date-fns';
import floor from 'lodash/floor';
import cloneDeep from 'lodash/cloneDeep';

export default {
  name: 'BaseLib',
  cloneDeep: cloneDeep,
  floor: floor,

  replaceAll(str, FindText, RepText) {
    var regExp = new RegExp(FindText, "g");
    return str.replace(regExp, RepText);
  },

  sleep(time) {
    return new Promise(resolve => setTimeout(resolve, time));
  },

  postMessage(message, param) {
    const msg = {
      eventType: message,
      eventInfo: param,
    };
    window.parent.postMessage(msg, '*');
  },

  loadXMLDoc(url, callback) {
    let xmlhttp = null;
    if (window.XMLHttpRequest) {
      xmlhttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
      xmlhttp = new window.ActiveXObject("Microsoft.XMLHTTP");
    }
    if (xmlhttp != null) {
      xmlhttp.onreadystatechange = callback;
      xmlhttp.open("GET", url, false);
      xmlhttp.send(null);
    }
    else {
      alert("Your browser does not support XMLHTTP.");
    }
  },

  genKey() {
    return format(new Date(), 'YYYYMMDDHHmmss');
  },

  uuid() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";

    var uuid = s.join("");
    return uuid;
  },

  /**
   * 获取某日凌晨时间戳
   * @param {Number} n 日偏移量，0为今日
   * @returns 本时区时间戳
   */
  getFirstTimeOfDay(n) {
    const dateInst = new Date();
    // 本时区毫秒偏移量
    const offsetTime = dateInst.getTimezoneOffset() * 60 * 1000;
    // 根据偏移量修正
    const curBaseLong = new Date().getTime() - offsetTime;
    // 获取今日天数
    const dayLong = parseInt(curBaseLong / 86400000);
    // 返回本时区时间戳
    return (dayLong + n) * 86400000 + offsetTime;
  },

  getDay(days) {
    const today = new Date().valueOf();
    const selday = new Date(today + (days * 3600 * 1000 * 24));
    const year = selday.getFullYear();
    const month = selday.getMonth() >= 9 ? selday.getMonth() + 1 : `0${(selday.getMonth() + 1)}`;
    const day = selday.getDate() >= 10 ? selday.getDate() : `0${selday.getDate()}`;
    return `${year}-${month}-${day}`;
  },

  checkEmit(root, event, paramObj) {
    const cbs = root._events[event];
    if (cbs && cbs.length > 0) {
      root.$emit(event, paramObj);
    } else {
      paramObj.callback();
    }
  }
};